#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的测试服务器 - 用于诊断连接问题
"""

from flask import Flask, request, jsonify, Response
from flask_cors import CORS, cross_origin
import json
import time

app = Flask(__name__)
CORS(app, origins=['*'])  # 允许所有来源

@app.route('/api/pose/status', methods=['GET'])
@cross_origin()
def get_status():
    """获取服务器状态"""
    return jsonify({
        'status': 'running',
        'message': '测试服务器运行正常'
    })

@app.route('/api/pose/realtime/start', methods=['POST'])
@cross_origin()
def start_realtime_processing():
    """开始实时处理（测试版本）"""
    try:
        print("收到开始实时处理请求")
        return jsonify({
            'success': True,
            'message': '开始实时处理（测试模式）'
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/pose/realtime/stop', methods=['POST'])
@cross_origin()
def stop_realtime_processing():
    """停止实时处理"""
    return jsonify({
        'success': True,
        'message': '已停止处理'
    })

@app.route('/api/pose/realtime/stream', methods=['GET'])
@cross_origin()
def stream_realtime_processing():
    """实时流式处理（SSE）- 测试版本"""
    def generate():
        print("开始SSE流")
        for i in range(10):  # 发送10条测试数据
            test_data = {
                'frame': i + 1,
                'total_frames': 10,
                'image': 'test_image_data',  # 简化的测试数据
                'detections': [
                    {
                        'track_id': 1,
                        'bbox': [100, 100, 200, 200],
                        'keypoints': [],
                        'confidence': 0.85
                    }
                ],
                'video_info': {
                    'width': 640,
                    'height': 480,
                    'fps': 30
                }
            }
            
            yield f"data: {json.dumps(test_data)}\n\n"
            time.sleep(1)  # 每秒发送一条数据
        
        yield f"data: {json.dumps({'complete': True})}\n\n"
        print("SSE流结束")
    
    response = Response(generate(), mimetype='text/event-stream')
    response.headers['Cache-Control'] = 'no-cache'
    response.headers['Connection'] = 'keep-alive'
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'Cache-Control'
    return response

@app.route('/', methods=['GET'])
def index():
    """首页"""
    return jsonify({
        'message': '简化测试服务器',
        'version': '1.0.0',
        'endpoints': [
            'GET /api/pose/status - 获取服务器状态',
            'POST /api/pose/realtime/start - 开始实时处理',
            'POST /api/pose/realtime/stop - 停止实时处理',
            'GET /api/pose/realtime/stream - 实时流式数据'
        ]
    })

if __name__ == '__main__':
    print("🚀 启动简化测试服务器...")
    print("📡 服务器地址: http://localhost:5000")
    print("🔧 用于诊断连接问题")
    
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)



